﻿'Params
'limit (Optional) : The number of results to fetch per page. Defaults to 30.
'page (Optional) : The page number to fetch. Defaults to first page.
'track (Required) : The track name
'artist (Optional) : Narrow your search by specifying an artist.
'api_key (Required) : A Last.fm API key.
'Auth
'This service does not require authentication. 

Public Structure TrackSearchResponse
	Dim lfmstatus As String
	Dim tracks() As Track
End Structure

Public Class TrackSearch
	Inherits BaseRequest
	Dim artist As String = ""
	Dim track As String = ""
	Dim page As String = ""
	Dim limit As String = ""

	Public xmlresponse As XDocument = Nothing

	Public Sub New(track As String, artist As String, limit As String, page As String)
		Me.artist = artist
		Me.track = track
		Me.page = page
		Me.limit = limit
	End Sub

	Public Sub sendRequest()
        InitializeMembers("track.Search")

		AddMember("track", track, True)
		AddMember("artist", artist, False)
		AddMember("limit", limit, False)
		AddMember("page", page, False)
		AddMember("api_key", My.Settings.api_key, True)

		xmlresponse = sendPOSTResponse()
	End Sub

	Public Function getResponse() As TrackSearchResponse
		Dim response As TrackSearchResponse = Nothing
        Dim count As Integer

        Try
            response.lfmstatus = xmlresponse.<lfm>.Attributes.ElementAt(0).Value
        Catch ex As Exception
            If response.lfmstatus <> "ok" Then
                Return Nothing
            End If
        End Try

		Try
			count = xmlresponse.<lfm>.<results>.<trackmatches>.<track>.Count()
		Catch ex As Exception
			Return response
		End Try
		If (count > 0) Then
			ReDim response.tracks(count - 1)
			For i As Integer = 0 To count - 1
				response.tracks(i) = New Track(xmlresponse.<lfm>.<results>.<trackmatches>.<track>(i))
			Next
		End If
		Return response
	End Function
End Class
